import { defineStore } from 'pinia';
import { store } from '@/store';
import projectSetting from '@/settings/projectSetting';
// import type { IheaderSetting, ImenuSetting, ImultiTabsSetting, IcrumbsSetting } from '/#/config';

import { storage } from '@/utils/Storage';

import { getMachineByMac } from '@/api/base/machine';
import { getGatherMachineByMachineCode } from '@/api/gather/machine';
import { listAlarm } from '@/api/base/alarm';
// import { cloumsMaterial } from '@render/api/base/material';

const {
  navMode,
  navTheme,
  isMobile,
  headerSetting,
  showFooter,
  menuSetting,
  multiTabsSetting,
  crumbsSetting,
  permissionMode,
  isPageAnimate,
  pageAnimateType,
  permissionMenu,
  permissionCheck,
  language,
} = projectSetting;

interface ProjectSettingState {
  navMode: string; //导航模式
  navTheme: string; //导航风格
  headerSetting: any; //顶部设置
  showFooter: boolean; //页脚
  menuSetting: any; //多标签
  multiTabsSetting: any; //多标签
  crumbsSetting: any; //面包屑
  permissionMode: string; //权限模式
  isPageAnimate: boolean; //是否开启路由动画
  pageAnimateType: string; //路由动画类型
  isMobile: boolean; // 是否处于移动端模式
  permissionMenu: boolean; // 是否校验菜单
  permissionCheck: boolean; // 是否校验按钮
  language: string; // 语言类型
  mac: string;
  factoryName: string;
  factoryChildName: string;
  machineData: any;
  defaultDistributeData: any;
  ip: string;
  isElectron: boolean;
  host: string;
  syncHostSqlite: boolean;
  plcConnect: Function;
  deleteChildProcess: Function;
  machineAlarmList: Array<any>;
  alarmList: Array<any>;
  collapsed: boolean;
}

let lang = storage.get('language') || language || 'zh';

const props: any = (window as any).$wujie?.props || null;

if (props) {
  const { app = {} } = props;

  if (app) {
    const { language = null } = app;

    if (language) {
      lang = language;
    }
  }
}

export const useProjectSettingStore = defineStore({
  id: 'app-project-setting',
  state: (): ProjectSettingState => ({
    navMode: navMode,
    navTheme,
    isMobile,
    headerSetting,
    showFooter,
    menuSetting,
    multiTabsSetting,
    crumbsSetting,
    permissionMode,
    isPageAnimate,
    pageAnimateType,
    permissionMenu,
    permissionCheck,
    language: lang,
    mac: '',
    ip: '',
    factoryName: '',
    factoryChildName: '',
    machineData: null,
    defaultDistributeData: null,
    isElectron: false,
    host: 'localhost',
    syncHostSqlite: false,
    plcConnect: () => null,
    deleteChildProcess: () => null,
    machineAlarmList: [],
    alarmList: [],
    collapsed: false,
  }),
  getters: {
    getNavMode(): string {
      return this.navMode;
    },
    getNavTheme(): string {
      return this.navTheme;
    },
    getIsMobile(): boolean {
      return this.isMobile;
    },
    getHeaderSetting(): object {
      return this.headerSetting;
    },
    getShowFooter(): boolean {
      return this.showFooter;
    },
    getMenuSetting(): object {
      return this.menuSetting;
    },
    getMultiTabsSetting(): object {
      return this.multiTabsSetting;
    },
    getCrumbsSetting(): object {
      return this.multiTabsSetting;
    },
    getPermissionMode(): string {
      return this.permissionMode;
    },
    getIsPageAnimate(): boolean {
      return this.isPageAnimate;
    },
    getPageAnimateType(): string {
      return this.pageAnimateType;
    },
    getMac() {
      return this.mac;
    },
    getIp() {
      return this.ip;
    },
  },
  actions: {
    setNavTheme(value: string): void {
      this.navTheme = value;
    },
    setIsMobile(value: boolean): void {
      this.isMobile = value;
    },
    setPermissionCheck(val) {
      this.permissionCheck = val;
    },
    setMacData(data) {
      const { mac, ip, host, syncHostSqlite } = data;

      this.mac = mac;

      this.ip = ip;

      this.host = host;

      this.syncHostSqlite = syncHostSqlite;
    },
    async setMachineData(data) {
      if (data.mac) {
        const res = await getMachineByMac({ mac: data.mac });

        if (res.data) {
          this.machineData = res.data;

          const res2 = await listAlarm({ machineCode: res.data.machineCode });

          if (res2.data?.length) {
            this.machineAlarmList = res2.data;
          }

          getGatherMachineByMachineCode({ machineCode: res.data.machineCode }).then((res1) => {
            if (res1.data?.length && window.electron) {
              setTimeout(() => {
                // window.electron.deleteChildProcess();

                window.electron.plcConnect({
                  list: res1.data,
                  machineCode: res.data.machineCode,
                });
              }, 0);
            }
          });

          // const res1 = await getGatherMachineByMachineCode({ machineCode: res.data.machineCode });

          // console.log(res1.data)

          // const res2 = await cloumsMaterial();

          // console.log(res2.data)

          // const list = [];

          // for (const item of res1.data[0].addressList) {
          //   const { parameterId, slaveId, startOffset, address, finsAddress, type, leng, decimalPlaces, byteOrder, s7Address, opcuaAddress, opcuaType, computedNum, computedType, funId } = item;

          //   let offset = 0;

          //   if (finsAddress.includes('W')) {
          //     const parts = finsAddress.split('.'); // 将finsAddress按照"."分割成两部分
          //     const row = parseInt(parts[0].substr(1)); // 提取第一部分并去掉前缀字母"W"，然后将其转换为整数
          //     const column = parseInt(parts[1]); // 提取第二部分并将其转换为整数
          //     const offsetIdNum = row * 16 + column; // 根据公式计算offsetIdNum

          //     offset = offsetIdNum;
          //   } else if (finsAddress.includes('D')) {
          //     const offsetIdNum = Number(finsAddress.replace('D', ''));

          //     offset = offsetIdNum;
          //   }

          //   list.push({
          //     plcId: res1.data[0].accessCode,
          //     type: type === 'bool' ? 'M' : 'D',
          //     leng,
          //     offset,
          //     startOffset:0,
          //     list: [
          //       {
          //         finsAddress,
          //         code: null,
          //         funId,
          //         type,
          //         leng,
          //         decimalPlaces,
          //         byteOrder,
          //         computedType,
          //         computedNum
          //       }
          //     ]
          //   })
          // }

          // if (list.length) {
          //   console.log(list)

          //   const aList = getDFFinsReadListFn(list)

          //   console.log(aList)
          // }
        }

        this.isElectron = true;
      }
    },
    updateAlarmList(list) {
      this.alarmList = [...list];
    },
    setCollapsed(val) {
      this.collapsed = val;
    },
  },
});

// Need to be used outside the setup
export function useProjectSettingStoreWithOut() {
  return useProjectSettingStore(store);
}
